package com.sad.jetpack.v1.datamodel.demo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.lifecycle.Lifecycle;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.sad.jetpack.v1.datamodel.api.DataModelProducerImpl;
import com.sad.jetpack.v1.datamodel.api.DataModelRequestImpl;
import com.sad.jetpack.v1.datamodel.api.DataSource;
import com.sad.jetpack.v1.datamodel.api.IDataModelObtainedCallback;
import com.sad.jetpack.v1.datamodel.api.IDataModelObtainedExceptionListener;
import com.sad.jetpack.v1.datamodel.api.IDataModelProducer;
import com.sad.jetpack.v1.datamodel.api.IDataModelRequest;
import com.sad.jetpack.v1.datamodel.api.IDataModelResponse;
import com.sad.jetpack.v1.datamodel.api.extension.cache.CacheUtil;
import com.sad.jetpack.v1.datamodel.api.extension.client.http.sse.SSEConnectionListener;
import com.sad.jetpack.v1.datamodel.api.extension.client.http.sse.SSEDataClient;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.DefaultIPCChatTextSession;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatAccessListener;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatDataType;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatHeader;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatSession;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatSessionManager;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatTextSessionListener;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCMember;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCServerAddress;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCTerminal;
import com.sad.jetpack.v1.datamodel.api.extension.engine.OkHttpEngineForStringByStringBody;
import com.sad.jetpack.v1.datamodel.api.extension.interceptor.DefaultCacheLoader;
import com.sad.jetpack.v1.datamodel.api.extension.interceptor.LogDataModelInterceptor;
import com.sad.jetpack.v1.datamodel.api.extension.interceptor.DefaultStringCacheDataModelInterceptor;
import com.sad.jetpack.v1.datamodel.api.utils.LogcatUtils;
import com.sad.jetpack.v1.datamodel.demo.testFuture.TestFutureMain;

import java.net.ServerSocket;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MainActivity extends AppCompatActivity {
    private AppCompatButton button_start;
    private TextView tv_console;
    private AppCompatButton button_cleanCache;
    private AppCompatButton button_ac2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DefaultCacheLoader.initCacheLoader(getApplicationContext());
        //configDataModel(dataModel);
        testServerSocket();
        initView();
        TestFutureMain.testGo(this);

    }

    private void initView() {
        button_start = findViewById(R.id.startTest);
        tv_console = findViewById(R.id.console);
        button_cleanCache = findViewById(R.id.cleanCache);
        button_ac2 = findViewById(R.id.ac2);
        button_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //test();
                testServerSocket();
            }
        });
        button_cleanCache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CacheUtil.clearAll();
            }
        });
        button_ac2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i=new Intent(new Intent(MainActivity.this, SecondActivity.class));
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        });
        EditText ed_chat_msg=findViewById(R.id.chatContent);
        findViewById(R.id.chatMsgSend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(ed_chat_msg.getText())){
                    String msg=ed_chat_msg.getText().toString();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Iterator<Map.Entry<String, IPCChatSessionManager>> iterator = sessionManagers.entrySet().iterator();
                            while (iterator.hasNext()){
                                Map.Entry<String, IPCChatSessionManager> next = iterator.next();
                                IPCChatSessionManager sessionManager=next.getValue();
                                try {
                                    sessionManager.getChatMessenger().syncSend(msg.getBytes(),-1,false);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }).start();
                }
            }
        });

        Fragment1 f1=new Fragment1();
        Bundle b=new Bundle();
        b.putInt("index",0);
        f1.setArguments(b);
        FragmentMaster.with(getSupportFragmentManager())
                .prePare(f1)
                .choiceMode()
                .addAllToContainer(R.id.fragment_container1)
                .hideAll(Lifecycle.State.STARTED)
                .show(0, Lifecycle.State.RESUMED);
        FragmentMaster.with(getSupportFragmentManager())
                .prePare(new Fragment1())
                .choiceMode()
                .addAllToContainer(R.id.fragment_container2)
                .hideAll(Lifecycle.State.STARTED)
                .show(0, Lifecycle.State.RESUMED);
    }


    private void testWebSocket(){

    }


    private Map <String,IPCChatSessionManager> sessionManagers=new ConcurrentHashMap<>();
    private void testServerSocket(){
        try {
            IPCMember selfMember=IPCMember.newInstance()
                    .setAlias("雷达峰1号监测站000215")
                    .setClientId("xcn105330")
                    .setDescription("表面是卫星武器，实则是监听地外文明。");
            IPCTerminal.newInstance(selfMember)
                    .listen(10821, true, new IPCChatAccessListener() {
                        @Override
                        public void onServerSocketCreated(IPCTerminal terminal,ServerSocket socket) {
                            IPCServerAddress.saveLocalAddress(getApplicationContext(),selfMember.getClientId(),socket.getLocalPort());
                        }

                        @Override
                        public boolean onCheckAccessPermission(IPCChatHeader header) {
                            return true;
                        }

                        @Override
                        public IPCChatSession onCreateSession(IPCChatHeader header) {

                            DefaultIPCChatTextSession session=new DefaultIPCChatTextSession(){
                                @Override
                                public IPCChatDataType chatDataType() {
                                    return header.getIntent().getChatDataType();
                                }
                            };
                            session.setTextSessionListener(new IPCChatTextSessionListener() {
                                @Override
                                public void onReadyToStart(IPCChatSessionManager sessionManager) {
                                    LogcatUtils.e("IPC测试-------------->监听端存储会话管理器信息："+sessionManager.getHeader().getFrom().getClientId());
                                    MainActivity.this.sessionManagers.put(sessionManager.getHeader().getFrom().getClientId(),sessionManager);
                                }

                                @Override
                                public void onChatText(IPCChatSessionManager sessionManager, ITextReader reader, String s) throws Exception {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            tv_console.append(s+"\n");
                                            LogcatUtils.e("IPC测试-------------->监听端接收信息："+s);
                                        }
                                    });

                                }
                            });
                            return session;
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private void threadTest(){

    }
    private void testClient(){
        SSEDataClient.newInstance()
                .connectionListener(new SSEConnectionListener() {
                    @Override
                    public void onSSEConnectionAlive(IDataModelRequest dataModelRequest) {

                    }

                    @Override
                    public void onSSEDataReceived(IDataModelRequest dataModelRequest, String data) {

                    }

                    @Override
                    public void onSSEConnectionClosed(IDataModelRequest dataModelRequest) {

                    }
                })
                .url("http://xxxx.xxx")
                .method(IDataModelRequest.Method.POST)
                .params("cscscacacacasc")
                .dataModelProducer("xxx")
                .exceptionListener(new IDataModelObtainedExceptionListener() {
                    @Override
                    public void onDataObtainedException(IDataModelRequest request, Throwable throwable) {

                    }
                })
                .execute();
    }

}